package server.util;

import server.Bootstrap;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class MyClassLoader  extends ClassLoader {
    private String projectName;

    public String getProjectName() {
        return projectName;
    }

    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }

    @Override
    protected Class<?> findClass(String name) {
        byte[] bytes=null;
        //将点替换成斜杠
        String fileName=name.replaceAll("\\.","/");
        StringBuilder sb=new StringBuilder(new Bootstrap().getProjectPath());
        sb.append("/");
        sb.append(fileName);
        sb.append(".class");


        try {
            InputStream is=new FileInputStream(new File(sb.toString()));
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            byte[] buf=new byte[1024];
            int r=0;
            while ((r=is.read(buf))!=-1){
                bos.write(buf,0,r);
            }
            bytes=bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        name=name.substring(name.lastIndexOf("classes")+8,name.length());
        return defineClass(name,bytes,0,bytes.length);
    }

    public static void main(String[] args) throws Exception{
        //自定义类加载器对象1
        MyClassLoader c1=new MyClassLoader();
        c1.setProjectName("servlet1");
        String className="servlet1.WEB-INF.classes.com.wxx.controller.TestController";
        //c1.findClass(className);
        //loadClass调用的就是findClass()
        Class clazz1=c1.loadClass(className);

        //自定义类加载器对象2
        MyClassLoader c2=new MyClassLoader();
        Class clazz2=c2.loadClass(className);

        System.out.println(clazz1.getClassLoader());
        System.out.println(clazz2.getClassLoader());

        if(clazz1!=clazz2) {
            System.out.println("不同的类加载器对象加载相同的class文件，会产生不同的类对象");
        }
//        }
//        Object obj1=clazz1.getDeclaredConstructor(new Class[]{String.class}).newInstance("自定义加载器加载进内存的");
//        Field fa=clazz1.getDeclaredField("a");
//
//        fa.setAccessible(true);//将私有变量设置成可以访问的权限
//        System.out.println(fa.toString());
        Method method2 = clazz1.getDeclaredMethod("print");
        method2.setAccessible(true);
        method2.invoke(clazz1.getDeclaredConstructor().newInstance());
        System.out.println("结束调用");
    }
}
